<template>
  <div>
    <!-- <div class="title">选择收货地址及配送时间后，将为您显示最终的优惠价格</div> -->
    <!-- 地址 -->
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @edit="getAddress"
      class="hiddenRadio"
    />
    <van-popup
      v-model="showAddress"
      position="bottom"
      :style="{ height: '50%' }"
      class="hiddenEdit"
    >
      <van-address-list
        v-model="chosenAddressId"
        :list="Addresslist"
        default-tag-text="默认"
        @edit="getAddress"
        @click-item="onClick_item"
      />
    </van-popup>

    <!-- 配送时间 -->
    <div class="deliver" @click="showPopup">
      <div style="padding-left: 10px">
        <span class="fontSize-m" style="font-weight: 600"
          ><van-icon name="underway-o" />配送时间</span
        >
      </div>
      <div style="text-align: right; padding: 10px">
        <p v-if="deliverTime == ''">
          请选择配送时间<van-icon name="arrow-down" />
        </p>
        <p v-else>配送时间:{{ deliverTime }}</p>
        <p class="fontColor fontSize-s">如选择次日配送，无法修改或取消订单</p>
      </div>
    </div>
    <van-popup v-model="show" position="bottom" :style="{ height: '50%' }">
      <van-datetime-picker
        v-model="currentDate"
        type="datehour"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        :filter="filter"
        @confirm="choseTime"
        @cancel="oncancel"
      />
    </van-popup>

    <!-- 38畅享大礼包 -->
    <div class="gift">
      <div style="width: 70%">
        <p class="fontColor">+38元&nbsp;&nbsp;畅享派对大礼包</p>
        <p class="fontSize-s">
          金喜满满生日礼包·金色蜡烛·蛋糕盒装饰丝带·蛋糕免费加大券
        </p>
      </div>
      <div style="width: 20%">
        <van-checkbox
          v-model="checked"
          shape="round"
          checked-color="#ff4001"
          @click="checked?total+=3800:total-=3800"
        ></van-checkbox>
      </div>
    </div>

    <!-- 订单列表 -->
    <van-card
      v-for="item in product"
      :key="item.gid"
      num="1"
      :price="item.cake_price"
      :desc="item.cake_description"
      :title="item.cakename"
      :thumb="item.cake_pic"
      style="backgroundcolor: #fff"
    >
      <template #footer>
        <div class="fontLeft">
          <van-collapse v-model="activeNames" accordion>
            <van-collapse-item title="[促销]点击查看详情" :name="item.gid">
              即日起至2021年12月31日，单笔订单购买蛋糕馆蛋糕赠【法式雪绒蛋糕·丝滑奶酪味】。本活动不与【雪域牛乳芝士】赠星级享甜礼包活动同享（如优惠券、储值卡、蛋糕券、兑换券、银行优惠等）。
            </van-collapse-item>
          </van-collapse>
        </div>
      </template>
    </van-card>

    <!-- 优惠券 -->
    <!-- 优惠券单元格 -->
    <van-coupon-cell
      :coupons="coupons"
      :chosen-coupon="chosenCoupon"
      @click="showList = true;total+=discount;"
    />
    <!-- 优惠券列表 -->
    <van-popup
      v-model="showList"
      round
      position="bottom"
      style="height: 90%; padding-top: 4px"
    >
      <van-coupon-list
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        :disabled-coupons="disabledCoupons"
        @change="onChange"
        @exchange="onExchange"
      />
    </van-popup>
    <!-- 结算 -->
    <van-submit-bar :price="total" button-text="结算" @submit="onSubmit"></van-submit-bar>
  </div>
</template>

<script>
import { Dialog } from 'vant';
export default {
  data() {
    return {
      // 结算是否全选
      allChecked:false,
      // 是否显示地址列表
      showAddress: false,
      // 被选择优惠券的下标
      chosenCoupon: -1,
      coupons: [],
      disabledCoupons: [],
      showList: false,
      // 折扣价格
      discount: 0,
      // 促销活动
      activeNames: 0,
      // 38礼包是否选中
      checked: false,
      show: false,
      // 配送地址
      chosenAddressId: 1,
      list: [],
      Addresslist: [],
      product: [],
      // 时间
      minDate: new Date(),
      maxDate: '',
      currentDate: new Date(),
      deliverTime: "", //配送时间
      total: 0,
      showWarn: false,
      order_id: 0,
    };
  },
  mounted () {
    let maxDate=this.moment(new Date()).add(1, 'M').hour(20).format('YYYY,MM,DD');
    this.maxDate=new Date(maxDate)
    let token=localStorage.getItem("token");
    this.$get('/v1/userAddress/userAddress',token).then(res=>{
      res.data.data.forEach(item => {
        item.id=item.aid
        if(item.isDefault){
          this.list[0]=item
          // console.log(this.list)
        }
      });
      this.Addresslist=res.data.data;
    });
    this.$get('/v1/coupon/get',token).then(res=>{
      let result=res.data.data;
      result.forEach(item => {
        item.originCondition*=100;
        item.denominations*=100;
        if(item.originCondition<this.total){
          this.coupons.push(item)
        }else{
          item.reason=`您的总金额还未达到${item.originCondition/100}元`
          this.disabledCoupons.push(item);
        }
      });
    })
    let cid=this.$route.query.id;
    this.$get('/v1/order/buy',{cid}).then(res=>{
      this.product=res.data.data
      this.total=this.product[0].cake_price*100;
    })
  },
  methods: {
    // 跳转地址列表
    getAddress() {
      this.showAddress = true;
      // 获取地址列表
    },
    // 点击任意地址后
    onClick_item(item){
      this.list.splice(0,1,item);
      this.showAddress=false
    },
    filter(type, options) {
      if (type === 'hour') {
        return options.filter((option) =>option>=8&&option<=20);
      }
      return options;
    },
    // 选择配送时间
    choseTime(val) {
      this.deliverTime=this.moment(val).format("YYYY年MM月DD日 hh:mm");
      // console.log(val.getHours());
      // console.log(this.deliverTime)
      this.show=false
    },
    // 取消选择配送时间
    oncancel() {
      this.show = false;
    },
    // 优惠券
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;
      this.discount=this.coupons[index].denominations||(100-this.coupons[index].discount)/100*this.coupons[index].originCondition;
    //console.log(this.discount)
      this.total-=this.discount;
    },
    onExchange(code) {
      this.coupons.push(coupon);
    },
    showPopup() {
      this.show = true;
    },
    // 结算
    onSubmit() {
      // console.log(this.deliverTime)
      if(!this.deliverTime){
        Dialog.alert({
        message: '您还没有选择配送时间',
        }).then(() => {
          // on close
        });
      }else{
        let orderId=this.moment(new Date()).unix()*1000+Math.ceil(Math.random()*1000);
        let params={orderId,price:this.total}
        this.$get('/v1/alipay/pay',params).then(res=>{
          let token=localStorage.getItem("token");
          let params={aid:this.list[0].aid,token,orderId,serve_time:this.deliverTime,total_price:this.total}
          this.$get('/v1/order/set',params).then(res=>{
            this.order_id=res.data.data[0].oid;
          })
          if(this.chosenCoupon!=-1){
            let yid=this.coupons[this.chosenCoupon].yid;
            this.$get('/v1/coupon/del',{yid}).then(res=>{
            })
          }
          let str = res.data.data;
          window.location.href=str;
        })
      }
    },
  },
  watch: {
    order_id(newValue, oldValue) {
      this.product.forEach(item=>{
        let params={order_id:newValue,product_id:item.cid,count:item.count,}
        this.$get('/v1/order/setDetail',params).then(res=>{
        })
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.title {
  width: 100%;
  background-color: #ff4001;
  font-size: 0.9375rem;
  color: #fff;
  font-size: 14px;
  text-align: center;
  line-height: 25px;
}
.van-address-list {
  margin-bottom: -4rem;
}
.hiddenRadio{
  .van-address-list__bottom,::v-deep .van-radio__icon {
    display: none;
}
}
.hiddenEdit{
  .van-address-list__bottom,::v-deep .van-icon-edit {
    display: none;
}
}
.deliver {
  margin: 0 10px;
  display: flex;
  height: 3.5rem;
  background-color: #fff;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  box-shadow: 2px 2px 6px 0px gray;
  border-radius: 5px;
}
// 畅享礼包
.gift {
  margin: 15px 10px;
  padding: 10px;
  background-color: #fff;
  font-size: 13px;
  display: flex;
  border-radius: 5px;
  // width: 100%;
  justify-content: space-between;
  height: 4.5rem;
  .van-checkbox {
    height: 100%;
    flex-direction: row-reverse;
    // align-items: center;
  }
}
// 字体样式
.fontColor {
  color: #ff4001;
}
.fontLeft {
  text-align: left;
}
.fontSize-s {
  font-size: 12px;
}
.fontSize-m {
  font-size: 14px;
}
// 促销
::v-deep .van-cell__title {
  color: #ff4001;
  font-size: 12px;
}
::v-deep .van-collapse-item__content {
  padding: 0 16px;
}
// 优惠券
.van-coupon-cell {
  margin: 10px 0px 60px;
}
::v-deep .van-coupon-list__exchange-bar {
  display: none;
}
</style>